package com.ljh.client;

import com.ljh.message.*;
import com.ljh.protocol.MessageCodecSharable;
import com.ljh.protocol.ProtocolFrameDecoder;
import com.ljh.server.handler.QuitHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        QuitHandler QUIT_HANDLER = new QuitHandler();

        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean isLoginSuccess = new AtomicBoolean(false);
        AtomicBoolean EXIT = new AtomicBoolean(false);
        Scanner in = new Scanner(System.in);

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
//                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    // ! 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // ! 3s 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE 事件
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    // ! ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        @Override // ? 用来触发特殊事件
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // ! 触发了写空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
                                log.debug("3s 没有写数据了，发送一个心跳包");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    ch.pipeline().addLast("clientHandler", new ChannelInboundHandlerAdapter() {
                        @Override // ? 处理服务器返回的响应
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.debug("message: {}", msg);
                            if (msg instanceof LoginResponseMessage response) {
                                System.out.println(response.getReason());
                                if (response.isSuccess()) {
                                    isLoginSuccess.set(true);
                                }
                                WAIT_FOR_LOGIN.countDown(); // ! 唤醒阻塞的 "systemIn" 线程
                            }
                        }

                        @Override // ? 连接建立后触发 active 事件，执行此方法
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // TODO 1. 登录
                            new Thread(() -> {
                                System.out.println("请输入用户名：");
                                String username = in.nextLine();
                                if(EXIT.get()){
                                    return;
                                }
                                System.out.println("请输入密码");
                                String password = in.nextLine();
                                if(EXIT.get()){
                                    return;
                                }
                                // TODO 2. 创建登录请求
                                LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);
                                // TODO 3. 发送数据到服务器
                                // ! 依此经过自定义协议编解码器、日志处理器 和 LTC 处理器
                                ctx.writeAndFlush(loginRequestMessage);
                                try {
                                    // TODO 4. 等待服务器返回响应
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                // TODO 5. 根据响应查看是否登录成功
                                if (!isLoginSuccess.get()) {
                                    ctx.channel().close();
                                    return;
                                }
                                while (true) {
                                    System.out.println("==================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    String command = in.nextLine();
                                    String[] options = command.split(" ");
                                    switch (options[0]) {
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username, options[1], options[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, options[1], options[2]));
                                            break;
                                        case "gcreate":
                                            Set<String> members = new HashSet<>(Arrays.asList(options[2].split(",")));
                                            members.add(username);
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(options[1], members));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(options[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username, options[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username, options[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }
                                }
                            }, "systemIn").start();
                        }

                        @Override // ? 在连接断开时触发
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("连接已经断开，按任意键退出..");
                            EXIT.set(true);
                        }

                        @Override // ? 在出现异常时触发
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("连接已经断开，按任意键退出..{}", cause.getMessage());
                            EXIT.set(true);
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
